package com.sann.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sann.common.utils.ResultCode;
import com.sann.eduservice.entity.subject.Subject;
import com.sann.eduservice.entity.subject.vo.SubjectData;
import com.sann.eduservice.service.SubjectService;
import com.sann.servicebase.handler.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 一行行读取Excel表格内容的监听器（除表头）.
 * 一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类.
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    /**
     * 因为SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
     * 不能实现数据库操作
     */
    @Autowired
    private SubjectService subjectService;
    public SubjectExcelListener(){}
    public SubjectExcelListener(SubjectService subjectService){
        this.subjectService = subjectService;
    }

    // 读取excel内容，一行一行进行读取
    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (data==null) {
            throw new GuliException(ResultCode.ERROR, "Excel文件为空");
        }
        /**
         * 判断一级分类是否重复,不重复就添加一级分类入库
         */
        Subject existOneSubject = this.existOneSubject(subjectService, data.getOneSubjectName());
        if (existOneSubject==null) {
            existOneSubject = new Subject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(data.getOneSubjectName());
            subjectService.save(existOneSubject);
        }

        // 获取一级分类id，供二级分类查询用(新增后mybatis会自动把新增数据的id主键值封装进对象并返回新增的对象)
        String pid = existOneSubject.getId();

        /**
         * 判断二级分类是否重复,不重复就添加二级分类入库
         */
        Subject existTwoSubject = this.existTwoSubject(subjectService, pid, data.getTwoSubjectName());
        if (existTwoSubject==null) {
            existTwoSubject = new Subject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(data.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }

    }

    //判断一级分类不能重复添加
    private Subject existOneSubject(SubjectService subjectService, String oneSubjectName){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", "0");
        wrapper.eq("title", oneSubjectName);
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }

    //判断二级分类不能重复添加
    private Subject existTwoSubject(SubjectService subjectService, String pid, String twoSubjectName){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", pid);
        wrapper.eq("title", twoSubjectName);
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
